package com.example.hello;

import com.example.hello.client.Form.BootstrapFormState;
import com.vaadin.shared.Connector;
import com.vaadin.ui.AbstractComponentContainer;
import com.vaadin.ui.Component;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class BootstrapForm extends AbstractComponentContainer {

    public enum Type {
        HORIZONTAL, INLINE, SEARCH, VERTICAL
    }

//    public BootstrapForm() {
//        this(Type.VERTICAL);
//    }
//
//    public BootstrapForm(BootstrapForm.Type type) {
//        setType(type);
//
//        setImmediate(true);
//    }

    @Override
    protected BootstrapFormState getState() {
        return (BootstrapFormState) super.getState();
    }

    public List<Component> getWidgets() {
        List<Component> widgets = new LinkedList<Component>();
        Iterator<Connector> itr = getState().getWidgets().iterator();
        while (itr.hasNext()) {
            widgets.add((Component) itr.next());
        }

        return widgets;
    }

    public void setWidgets(List<Component> widgets) {
        List<Connector> connectorList = new LinkedList<Connector>();
        Iterator<Component> itr = widgets.iterator();
        while (itr.hasNext()) {
            connectorList.add(itr.next());
        }

        getState().setWidgets(connectorList);
    }

    public void addWidget(Component widget) {
        addWidget(widget, getWidgets().size());
    }

    public void addWidget(Component widget, int index) {
        if (widget.getParent() != null) {
            throw new IllegalArgumentException("Given button already has a parent component");
        }

        getState().addWidget(widget, index);
        super.addComponent(widget);

        markAsDirty();
    }

    public void removeWidget(Component widget) {
        if (!getState().getWidgets().contains(widget)) {
            return;
        }

        getState().removeWidget(widget);
        super.removeComponent(widget);

        markAsDirty();
    }

    public String getTarget() {
        return getState().getTarget();
    }

    public void setTarget(String target) {
        getState().setTarget(target);
    }

    public Type getType() {
        return Type.valueOf(getState().getType());
    }

    public void setType(Type type) {
        getState().setType(type.toString());
    }

    @Override
    public void replaceComponent(Component oldComponent, Component newComponent) {

    }

    @Override
    public int getComponentCount() {
        return getWidgets().size();
    }

    @Override
    public Iterator<Component> iterator() {
        return getWidgets().iterator();
    }

}